<template>
  <basic-layout show-tab-bar>
    <custom-nav-bar title="明细" />
    <nut-cell title="选择日期" :desc="popupDesc" @tap="show = true"></nut-cell>
    <nut-popup v-model:visible="show" position="bottom">
      <nut-date-picker
        v-model="currentDate"
        type="year-month"
        title="日期选择"
        :min-date="new Date(2015, 0, 1)"
        :max-date="new Date()"
        :is-show-chinese="true"
        @confirm="confirm"
      ></nut-date-picker>
    </nut-popup>
    <nut-row type="flex" justify="space-around">
      <nut-col :span="6">
        <div>月总收入</div>
        <div>￥{{ totalIncome }}</div>
      </nut-col>
      <nut-col :span="6">
        <div>月总支出</div>
        <div>￥{{ totalExpense }}</div>
      </nut-col>
    </nut-row>
    <nut-divider />
    <div v-if="groupList.length > 0">
      <nut-collapse v-model="activeNames">
        <nut-collapse-item v-for="(group, index) in groupList" :key="index" :title="getTitle(group)" :name="index">
          <nut-row type="flex" justify="space-between">
            <nut-col :span="6">&#12288;</nut-col>
            <nut-col :span="9">{{ getTotal(group) }}</nut-col>
          </nut-row>
          <div class="items">
            <div
              v-for="(item, index) in group.items"
              :key="index"
              class="item"
              @tap="Taro.navigateTo({ url: `../record/index?id=${item.id}` })"
            >
              <nut-row>
                <nut-col :span="4" class="selected">
                  <div class="tagItemImg relative h-0 pb-full w-full">
                    <img :src="`https://img.xxsoftware.top/svg/${item.tag.name}.svg`" mode="widthFix" />
                  </div>
                </nut-col>
                <nut-col :span="4">&#12288;</nut-col>
                <nut-col :span="8">
                  <div :style="`line-height: ${lineHeight};`">{{ item.tag.value }}</div>
                </nut-col>
                <nut-col :span="2">&#12288;</nut-col>
                <nut-col :span="6">
                  <div :style="`line-height: ${lineHeight};`">{{ getAmount(item) }}</div>
                </nut-col>
              </nut-row>
            </div>
          </div>
        </nut-collapse-item>
      </nut-collapse>
    </div>
    <div v-else class="reverse">
      <Blank />
    </div>
  </basic-layout>
</template>

<script setup lang="ts">
import Taro, { useDidShow } from '@tarojs/taro';
import dayjs from 'dayjs';
import { useTagStore } from '@/store/modules/tag';
import clone from '@/lib/clone';
const activeNames = ref([0]);
const show = ref(false);
const popupDesc = ref(
  `${dayjs().year()}年-${dayjs().month() + 1 > 9 ? dayjs().month() + 1 : `0${dayjs().month() + 1}`}月`
);
const tagStore = useTagStore();
const currentDate = ref(new Date());
const year = ref(dayjs().year().toString());
const month = ref((dayjs().month() + 1).toString());
const lineHeight = ref('');
useDidShow(() => {
  if (groupList.value.length) {
    Taro.nextTick(() => {
      Taro.createSelectorQuery()
        .select('.item')
        .boundingClientRect()
        .exec(res => {
          if (res) {
            lineHeight.value = `${res[0].height}px`;
          }
        });
    });
  }
});

function toWeekday(value: number) {
  if (value >= 0 && value <= 6) {
    return ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][value];
  }
}

function getTitle(group: Group) {
  const day = dayjs(group.name);
  const now = dayjs();
  if (day.isSame(now, 'day')) {
    return `今天 ${toWeekday(day.day())}`;
  } else if (day.isSame(now.subtract(1, 'day'), 'day')) {
    return `昨天 ${toWeekday(day.day())}`;
  } else if (day.isSame(now.subtract(2, 'day'), 'day')) {
    return `前天 ${toWeekday(day.day())}`;
  } else if (day.isSame(now, 'year')) {
    return `${day.format('M月D日')} ${toWeekday(day.day())}`;
  }
  return `${day.format('YYYY年M月')}`;
}

function getTotal(group: Group) {
  let total = 0;
  let item: RecordItem;
  for (item of group.items) {
    if (item.type === '0') {
      total -= Number(item.amount);
    } else if (item.type === '1') {
      total += Number(item.amount);
    }
  }
  if (total <= 0) {
    return `日支出: ¥${Math.abs(total)}`;
  }
  return `日收入: ¥${Math.abs(total)}`;
}

function getAmount(record: RecordItem) {
  if (record.type === '1') {
    return record.amount;
  }
  return -record.amount;
}
type Group = {
  name: string;
  items: RecordItem[];
};
const groupList = computed(() => {
  const result: Group[] = [];
  const names: string[] = [];
  // 对记录排序
  const sortedRecordList = clone<RecordItem[]>(tagStore.recordList)
    .filter(
      item =>
        dayjs(item.createAt).year() === parseInt(year.value) &&
        dayjs(item.createAt).month() + 1 === parseInt(month.value)
    )
    .sort((b, a) => {
      return dayjs(a.createAt).valueOf() - dayjs(b.createAt).valueOf();
    });
  let record: RecordItem;
  for (record of sortedRecordList) {
    let date: string;
    if (year.value === dayjs().year().toString()) {
      // 今年的数据按天分组
      date = dayjs(record.createAt).toISOString().split('T')[0];
    } else {
      // 以前的数据按月分组
      date = dayjs(record.createAt).format('YYYY-MM');
    }

    const index = names.indexOf(date);
    if (index < 0) {
      names.push(date);
      result.push({ name: date, items: [record] });
    } else {
      result[index].items.push(record);
    }
  }
  return result;
});

const totalIncome = computed(() => {
  let total = 0;

  groupList.value.forEach(group => {
    group.items.forEach(record => {
      if (record.type === '1') {
        total += Number(record.amount);
      }
    });
  });
  return total;
});
const totalExpense = computed(() => {
  let total = 0;
  groupList.value.forEach(group => {
    group.items.forEach(record => {
      if (record.type === '0') {
        total += Number(record.amount);
      }
    });
  });
  return total;
});

const confirm = ({ selectedValue, selectedOptions }) => {
  show.value = false;
  popupDesc.value = selectedOptions.map((val: any) => val.text).join('-');
  Taro.showToast({
    title: selectedOptions.map((val: any) => val.text).join('-')
  });
  console.log(selectedValue, selectedOptions);
  year.value = selectedOptions[0].value;
  month.value = selectedOptions[1].value;
};

/** 设置页面属性 */
definePageConfig({
  navigationBarTitleText: '明细'
});
</script>

<style>
.nut-popup.nut-popup--bottom {
  bottom: var(--nut-tabbar-height, 100rpx);
}
</style>
